import { createRouter, createWebHashHistory } from "vue-router";
import { publicRoutes } from "./modules/publicRoutes";
import store from "../store";
import { ElLoading } from "element-plus";
import { getItem } from "../utils/storage";
import { TOKEN } from "../constant";

const router = createRouter({
  history: createWebHashHistory(),
  routes: publicRoutes,
});
const whiteList = ['/login']
// 路由守卫
router.beforeEach(async (to, from, next) => {
  let token = getItem(TOKEN) || '';
  if(token) {
    if (to.path === '/login'){
      next('/')
    }else {
      if(!store.getters.hasUserInfo) {
        const loadingInstance = ElLoading.service({
          lock: true,
          text: "努力的加载中...",
          background: "rgba(0, 0, 0, 0.4)",
        });
        try {
          const {menus} = await store.dispatch("user/getUserInfo")
          const filterRoutes = await store.dispatch(
            'permission/filterRoutes',
            menus
          )
          // 利用 addRoute 循环添加
          filterRoutes.forEach(item => {
            router.addRoute('layout',item)
          })
          loadingInstance.close();
          // 添加完动态路由之后，需要在进行一次主动跳转
          return next(to.path)
        } catch (error) {
          console.error(error);
          loadingInstance.close();
          return next(to.path);
        }
      }
      next()
    }
  } else {
    // 未登录，暂时只能访问首页
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
});

export function resetRouter () {
  if (
    store.getters.userInfo &&
    store.getters.userInfo.permission &&
    store.getters.userInfo.permission.menus
  ) {
    const menus = store.getters.menus
    menus.forEach((menu) => {
      router.removeRoute(menu)
    })
  }
}
export default router;
